<?php

namespace app\web\controller;

use app\web\jwt\Jwts;
use douyin\Dy;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use app\commons\model\Member;
use app\web\jwt\JwtsMac;

class Login
{
    public function index(Member $member){
        $data = request()->param();
        $validate = new \app\web\validate\Login();
        if (!$validate->check($data)) {
            throw new ValidateException($validate->getError());
        }
        $equipment = $data['equipment'] ?? '';
        try {
            //获取accesstoken
            $data = Dy::getAccessToken($data['code']);
            //获取access_token成功，获取用户信息
            $access_token = $data['data']['access_token'];
//            $access_token = 'act.10ae77caee0e3ef4bff30ecd08c518fbL8JDWedTcg8AIE3weR8cOMXwVTeN';
            $openid = $data['data']['open_id'];
//            $openid = '194e2fb3-327d-4ad3-90cf-40496ff05668';
            //判断是否存在用户
            $userId = $this->getUser($openid);
            //验证设备码
            $mac = [];
            Log::info('请求登录信息：');
            Log::info($data);
            if($equipment){
                $macData = JwtsMac::verifyToken($equipment);
                if(empty($macData)) throw new ValidateException('设备授权码非法！');
                if($macData['exp'] < time()) throw new ValidateException('设备授权码已过期，请重新扫码！');
                $redis_name = 'douyin:mac_cache:'.md5($equipment);
                $mac = ['mac_id'=>$macData['data']->mac_id,'redis_name'=>$redis_name];//设备ID,cache
            }
            if($userId){
                //更新用户access_token
                Log::info('登录信息：');
                Log::info($data);
                $res = Member::where(['id'=>$userId])->update(['access_token'=>$access_token]);
                $datas = ['access_token'=>Jwts::getToken($userId,$mac),'exp_time'=>7200];
                return json(['data'=>$datas,'code'=>200],200);
                return jsonp();
            }
            //获取用户信息
            $userInfoData = Dy::getUserInfo($openid,$access_token);
            //获取用户信息成功，入库，返回登录成功
            $config = get_sysset();
            $mobile = '';
            if(isset($userInfoData['data']['encrypt_mobile'])) $mobile = decryptdy($userInfoData['data']['encrypt_mobile'],$config['basic']['client_secret']);//前提需要授权的时候应许获取手机号码
            $province = $userInfoData['data']['province'];//省份
            $avatar = $userInfoData['data']['avatar'];//头像
            $e_account_role = $userInfoData['data']['e_account_role'];//账号类型
            $open_id= $userInfoData['data']['open_id'];//用户在当前平台唯一标识
            $nickname = $userInfoData['data']['nickname'];//昵称
            $city = $userInfoData['data']['city'];//城市
            $country = $userInfoData['data']['country'];//国家
            $gender = $userInfoData['data']['gender'];//性别，0，未知，1男，2，女；
            $memberData = [
                'mobile'=>$mobile,
                'openid'=>$open_id,
                'gender'=>$gender,
                'avatar'=>$avatar,
                'city'=>$city,
                'province'=>$province,
                'access_token'=>$access_token,
                'nickname'=>$nickname,
                'country'=>$country,
                'pt_openid'=>create_open_id('dyde-e',22),//平台自己的唯一凭据
            ];
            Log::info($mobile);
            $memberRes = $member->allowField(true)->save($memberData);
            if(!$memberRes){
                throw new ValidateException('登录失败！');
            }
            //返回生成token
            $token = Jwts::getToken($member->id,$mac);
            return jsonp(['access_token'=>$token,'exp_time'=>7200]);
        }catch (Exception $exception){
            Log::info('登录错误日志：');
            Log::info($exception->getMessage());
            return jsonp_error(422,$exception->getMessage());
        }

    }

    /**
     * 获取用户信息
     * @param $openid
     */
    public function getUser($openid){
        $user = Member::where(['openid'=>$openid])->find();
        if($user){
            return $user['id'];
        }
        return 0;
    }
}